package mvc.utils;

import java.io.File;
import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import mvc.bean.MvcBean;

import org.jdom.Document;
import org.jdom.Element;
import org.jdom.JDOMException;
import org.jdom.input.SAXBuilder;



public class MvcUtils {
	
	/**
	 * 解析xml文件
	 * @param xmlName
	 * @return
	 * @throws IOException 
	 * @throws JDOMException 
	 */
	public static Map<String, MvcBean> mvcUtils(String xmlName) throws JDOMException, IOException{
		Map<String, MvcBean> map=new HashMap<String, MvcBean>();
		SAXBuilder builder=new SAXBuilder();
		Document document=builder.build(new File(xmlName));
		Element root=document.getRootElement();
		Element actionMapping=root.getChild("action-mapping");
		List<Element> actionList=actionMapping.getChildren();
		for(Element e:actionList){
			MvcBean bean=new MvcBean();
			String name=e.getAttributeValue("name");
			bean.setName(name);
			String type=e.getAttributeValue("type");
			bean.setType(type);
			String path=e.getAttributeValue("path");
			bean.setPath(path);
			Element beans=root.getChild("beans");
			List<Element> beansList=beans.getChildren();
			for(Element t:beansList){
				String beanName=t.getAttributeValue("name");
				if(name.equals(beanName)){
					String beanClass=t.getAttributeValue("class");
					bean.setBeanClass(beanClass);
					break;
				}
			}
			List<Element> forword=e.getChildren();
			Map<String,String> fmap=new HashMap();
			for(Element f:forword){
				String fname=f.getAttributeValue("name");
				String fvalue=f.getAttributeValue("value");
				fmap.put(fname, fvalue);
				
			}
			bean.setMap(fmap);
			map.put(path, bean);
		}
		return map;
	}
}
